import { appConfig } from './../global/ConstUrl';
import { Injectable } from "@angular/core";
import { ActionSheetController, Events, LoadingController } from "ionic-angular";
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { ImagePicker } from '@ionic-native/image-picker';
import { NoticeService } from "./notice-service";
import { MediaCapture, MediaFile, CaptureError,  CaptureVideoOptions } from '@ionic-native/media-capture';

@Injectable()
export class ImgService {
  uploadSuccess: any;
  uploadError: any;
  constructor(
    private mediaCapture: MediaCapture,
    private actionSheetCtrl: ActionSheetController,
    private noticeSer: NoticeService,
    private transfer: FileTransfer,
    private camera: Camera,
    private imagePicker: ImagePicker,
    public loadingCtrl: LoadingController,
    private events: Events
  ) { }
  type: string;
  showPicActionSheet(type, cd) {
    this.type = type;
    this.useASComponent(cd);
  }

  // 使用ionic中的ActionSheet组件
  private useASComponent(cd) {
    let actionSheet = this.actionSheetCtrl.create({
      buttons: [
        {
          text: '拍照',
          handler: () => {
            this.startCamera(cd);
          }
        }, {
          text: '从相册选择',
          handler: () => {
            this.openImgPicker(cd);
          }
        }, {
          text: '取消',
          role: 'cancel',
          handler: () => { }
        }
      ]
    });
    actionSheet.present();
  }
  /**
   * 录制视频
   * @param cd 
   */
  public startMedia(cd) {
    let options: CaptureVideoOptions = { limit: 1,duration:20, quality:0 };
    this.mediaCapture.captureVideo(options)
      .then((data: MediaFile[]) => {
        alert(JSON.stringify(data));
        
        this.uploadVoide(data[0].fullPath, cd);
      },
      (err: CaptureError) => {
        
        this.noticeSer.showToast('错误:' + err); //错误：无法使用拍照功能！
      }
      );
  }


  // 启动拍照功能
  private startCamera(cd) {
    const options: CameraOptions = {
      quality: 65,
      destinationType: 1, //选择返回值的格式。  默认是FILE_URI。DATA_URL：0，以base64编码的字符串返回图像，FILE_URI：1，返回图像文件URI，NATIVE_URI：2返回图像原生URI（例如，assets-library：// iOS或content：// Android）
      sourceType: 1, // Camera.PictureSourceType.CAMERA,
      encodingType: 0, // Camera.EncodingType.JPEG,
      mediaType: 0, // Camera.MediaType.PICTURE,
      correctOrientation: true
    };
    this.camera.getPicture(options).then((image) => {
      alert(JSON.stringify(image));
      this.uploadImg(image, cd);
    }, (err) => {
      this.noticeSer.showToast('错误:' + err); //错误：无法使用拍照功能！
    });
  }
  // 打开手机相册
  private openImgPicker(cd) {
    let temp = '';
    // 调用相册时传入的参数
    const options = {
      maximumImagesCount: 1, //选择一张图片
      quality: 65
    };
    this.imagePicker.getPictures(options).then((results) => {
      for (var i = 0; i < results.length; i++) {
        temp = results[i];
      }
      this.uploadImg(temp, cd);
    }, (err) => {
      this.noticeSer.showToast('错误:' + err); //错误：无法从手机相册中选择图片！
    });
  }
  loading;
  // 上传图片
  private uploadImg(path: string, cd) {
    this.loading = this.loadingCtrl.create({
      content: '上传图片中...'
    });
    this.loading.present();
    var imgExt = 'jpg'; // 默认为jpg格式
    try {
      const fileTransfer: FileTransferObject = this.transfer.create();

      let options: FileUploadOptions = {
        fileKey: 'userfile',
        fileName: `avatar.${imgExt}`,
        headers: {
          "DeviceKey": this.getLocalStorage("DeviceKey"),
          "DeviceType": this.getLocalStorage("DeviceType"),
          "AppVersion": this.getLocalStorage("AppVersion"),
          "Ticket": this.getLocalStorage("Ticket"),
          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' // 不加入 发生错误！！
        },
      }
      let url = appConfig.appUrl + "/V1/Uploadpic?ResourceType=" + this.type;
      fileTransfer.upload(path, url, options)
        .then((data) => {
          this.events.publish('upload:success');
          cd(data);
          this.loading.dismiss();
        }, (err) => {
          alert(JSON.stringify(err));
        })
    } catch (error) {
      alert(JSON.stringify(error));
    }
  }

  /**
   * 上传视频
   * @param path 
   * @param cd 
   */
  private uploadVoide(path, cd) {
    const fileTransfer: FileTransferObject = this.transfer.create();
    let url = appConfig.appUrl + "V1/UploadResourceFile";
    var imgExt = "mp4";
    let options: FileUploadOptions = {
      fileKey: 'userfile',
      fileName: `avatar.${imgExt}`,
      headers: {
        "DeviceKey": this.getLocalStorage("DeviceKey"),
        "DeviceType": this.getLocalStorage("DeviceType"),
        "AppVersion": this.getLocalStorage("AppVersion"),
        "Ticket": this.getLocalStorage("Ticket"),
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' // 不加入 发生错误！！
      }
    }
    this.loading = this.loadingCtrl.create({
      content: '上传视频中...'
    });
    this.loading.present();

    fileTransfer.upload(path, url, options)
      .then((data) => {
        alert("上传成功");
        this.events.publish('upload:success');
        cd(data);
        this.loading.dismiss();
      }, (err) => {
        alert(JSON.stringify(err));
        alert("失败");
        this.events.publish('upload:fail');
        this.loading.dismiss();
      });
  }

	/**
	 * 读取LocalStorage
	 * @param key 
	 */
  getLocalStorage(key: string) {
    let value = localStorage.getItem(key);
    if (value && value != undefined && value != null) {
      return value;
    }
    return null;
  }




}
